<template>
  <div class="app-version-container">
    <table-page
      width="100%"
      class="app-table"
      ref="tablePage"
      :tableData="tableData"
      :tableColumn="tableColumn"
      :isIndex="true"
      :isSelection="false"
      :total="pages.total"
      :pageSize="pages.pageSize"
      :currentPage="pages.pageNum"
      @sizeChange="handleSizeChange"
      @currentChange="handleCurrentChange"
    >
      <template #handle>
        <el-button class="m_96" type="primary" v-hasPermi="['CentralControl.PackageVersion.Create']" icon="el-icon-plus" @click="handleAddDialog">
          新增
        </el-button>
      </template>
    </table-page>

    <!-- 新增/查看 -->
    <el-dialog
      width="520px"
      class="app-dialog"
      v-if="visible"
      :title="dialogTitle"
      :visible.sync="visible"
      :before-close="handleDialogClose"
      :close-on-click-modal="false"
    >
      <div class="container">
        <Form
          ref="appForm"
          v-model="dialogData"
          label-width="100px"
          :config="dialogConfig"
          :isReadonly="isReadonly"
          :hide-required-asterisk="isReadonly"
        >
          <template #packageAddress v-if="!isReadonly">
            <el-upload
              ref="upload"
              class="upload-demo"
              :action="`${public_config.file_api}/api/file-management/files/upload`"
              :on-remove="handleRemove"
              :on-success="handleLocalSuccess"
              :headers="headers"
              :before-upload="beforeLocalUpload"
              :file-list="fileList"
            >
              <el-button style="background-color: #1890ff; color: white" size="small" type="primary">上传安装包</el-button>
            </el-upload>
            <p style="color: #ec9713; font-size: 13px; margin-top: 0px">当前附件仅支持wgt、apk类型文件</p>
          </template>
          <template #packageAddress v-else>
            {{ dialogData.packageAddress }}
          </template>
        </Form>
      </div>
      <span slot="footer" class="dialog-footer" v-if="!isReadonly">
        <el-button @click="handleDialogClose">取 消</el-button>
        <el-button type="primary" @click="handleDialogSubmit">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 二维码 -->
    <el-dialog
      width="300px"
      class="app-dialog qr-dialog"
      title="查看二维码"
      :visible.sync="qrVisible"
      :before-close="handleQrDialogClose"
      :close-on-click-modal="false"
    >
      <img :src="qrCode" width="192" style="text-align: center" />
    </el-dialog>
  </div>
</template>

<script>
import QRCode from 'qrcode'
import Form from '@/components/Form'
import TablePage from '@/components/TablePage'
import { getToken } from '@/utils/auth'
import { getAuthConfig } from '@/api/org'
import {
  getAppVersions,
  detailAppVersions,
  addAppVersions,
  delAppVersions,
  putAppVersions,
  publishAppVersions,
  appDropDownList,
} from '@/api/appVersion'
export default {
  name: 'AppVersion',
  components: { Form, TablePage },
  data: function () {
    return {
      headers: {
        Authorization: 'Bearer ' + getToken(),
      },
      tableData: [],
      tableColumn: [
        {
          label: 'APP名称',
          prop: 'packageName',
        },
        {
          label: '客户端',
          prop: 'clientTypeName',
        },
        {
          label: '版本号',
          prop: 'version',
        },
        {
          label: '升级类型',
          prop: 'updateStrengthName',
        },
        {
          label: '版本内容',
          prop: 'remark',
        },
        {
          label: '发布人',
          prop: 'creator',
        },
        {
          label: '发布时间',
          prop: 'publishTime',
        },
        {
          label: '操作',
          prop: 'action',
          fixed: 'right',
          width: 250,
          type: 'button',
          buttons: [
            {
              label: '查看',
              type: 'text',
              color: 'rgba(0, 118, 255, 1)',
              method: 'handleDetail',
            },
            {
              label: '编辑',
              type: 'text',
              hide: 'publishStatus',
              hideValue: [0],
              color: 'rgba(0, 118, 255, 1)',
              method: 'handleEdit',
              policy: ['CentralControl.PackageVersion.Update'],
            },
            {
              label: '二维码',
              type: 'text',
              hide: 'fullPackageUpdate',
              hideValue: [true],
              color: 'rgba(0, 118, 255, 1)',
              method: 'handleQRCode',
              policy: ['CentralControl.PackageVersion.QRCode'],
            },
            {
              label: '发布',
              type: 'text',
              hide: 'publishStatus',
              hideValue: [0, 2],
              color: 'rgba(0, 118, 255, 1)',
              method: 'handlePublish',
              policy: ['CentralControl.PackageVersion.Release'],
            },
            {
              label: '删除',
              type: 'text',
              hide: 'publishStatus',
              hideValue: [0, 2],
              color: '#F37272',
              method: 'handleDelete',
              policy: ['CentralControl.PackageVersion.Delete'],
            },
          ],
        },
      ],
      qrCode: null,
      qrVisible: false,
      visible: false,
      dialogTitle: '',
      dialogData: {},
      dialogisDetail: false,
      dialogConfig: [
        {
          label: '所属系统组织:',
          prop: 'organizationType',
          type: 'radio',
          options: [
            { label: 'CRM', value: 0 },
            { label: 'TMS', value: 1 },
          ],
          rules: [{ required: true, trigger: 'blur', message: '请选择所属系统组织' }],
        },
        {
          label: 'APP名称:',
          prop: 'packageName',
          type: 'input',
          slotTitle: 'APP信息',
          maxlength: 20,
          showWordLimit: true,
          rules: [{ required: true, trigger: ['change', 'blur'], message: '请输入APP名称' }],
        },
        {
          label: '客户端:',
          prop: 'clientType',
          type: 'radio',
          options: [
            { label: 'iOS', value: 1 },
            { label: '安卓', value: 0 },
          ],
          rules: [{ required: true, trigger: ['change', 'blur'], message: '请选择客户端类型' }],
        },
        {
          label: '发布类型:',
          prop: 'type',
          type: 'radio',
          hide: 'clientType',
          hideValue: [1],
          options: [{ label: 'appstore', value: 1 }],
          rules: [{ required: true, trigger: ['change'], message: '请选择发布类型' }],
        },
        {
          label: '   ',
          prop: 'iosUrl',
          type: 'input',
          hide: 'clientType',
          hideValue: [1],
          slotBefore: 'Http://',
          placeholder: '请输入',
          rules: [{ required: true, trigger: ['change'], message: '请输入iosUrl' }],
        },
        {
          label: '安装包:',
          render: true,
          prop: 'packageAddress',
          hide: 'clientType',
          hideValue: [0],
          rules: [{ required: true, trigger: ['change'], message: '请上传安装包' }],
        },
        {
          label: '版本号:',
          prop: 'version',
          type: 'input',
          slotBefore: 'V',
          placeholder: '版本号 *.*.*',
          rules: [
            { required: true, trigger: ['change', 'blur'], message: '请输入版本号' },
            { required: true, trigger: ['change', 'blur'], validator: this.validAppVersion },
          ],
        },
        {
          label: '版本内容:',
          prop: 'remark',
          type: 'textarea',
          rules: [{ required: true, trigger: ['change', 'blur'], message: '请输入版本内容' }],
        },
        {
          label: '发布时间:',
          prop: 'publishTime',
          type: 'datetime',
          slotTitle: '升级信息',
          rules: [{ required: true, trigger: ['change', 'blur'], message: '请选择发布时间' }],
        },
        {
          label: '升级类型:',
          prop: 'updateStrength',
          type: 'radio',
          options: [
            { label: '强制升级', value: 2 },
            { label: '强提示升级', value: 1 },
            { label: '弱提示升级', value: 0 },
          ],
          rules: [{ required: true, trigger: ['change', 'blur'], message: '请选择升级类型' }],
        },
        {
          label: '打包类型:',
          prop: 'fullPackageUpdate',
          type: 'radio',
          options: [
            { label: '整包更新', value: true },
            { label: '部分更新', value: false },
          ],
          rules: [{ required: true, trigger: ['change', 'blur'], message: '请选择打包类型' }],
        },
        {
          label: '最低兼容版本:',
          prop: 'minimumVersion',
          type: 'select',
          hide: 'fullPackageUpdate',
          hideValue: [false],
          options: [],
          async: this.getDropDownList,
        },
      ],
      fileList: [],
      dropDownList: [],
      pages: {
        total: 0,
        pageNum: 1,
        pageSize: 10,
      },
    }
  },
  watch: {
    ['dialogData.clientType']: function (nval) {
      this.dialogData.type = nval == 1 ? 1 : null
    },
  },
  computed: {
    isReadonly() {
      return !!this.dialogData.id && this.dialogisDetail
    },
  },
  created() {
    this.getTableData()
  },
  mounted() {
    // 详情
    this.$bus.$on('handleDetail', rows => {
      this.dialogTitle = 'APP版本'
      this.dialogisDetail = true
      this.dialogData = { ...rows, minimumVersion: rows.minimumVersionId }
      this.visible = true
    })

    // 编辑
    this.$bus.$on('handleEdit', async rows => {
      const res = await detailAppVersions({ id: rows.id })
      this.visible = true
      this.dialogTitle = '编辑版本'
      this.dialogData = { ...res }
      this.fileList.push({
        name: res.fileName,
        url: res.packageAddress,
      })
    })

    // 二维码
    this.$bus.$on('handleQRCode', rows => {
      this.qrVisible = true
      this.$nextTick(() => {
        QRCode.toDataURL(rows.packageAddress, { width: 192, margin: 1 }).then(res => {
          this.qrCode = res
        })
      })
    })

    //发布
    this.$bus.$on('handlePublish', rows => {
      this.$confirm(`确定要发布吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        publishAppVersions({ id: rows.id }).then(result => {
          this.$message.success('发布成功')
          this.getTableData()
        })
      })
    })

    //删除
    this.$bus.$on('handleDelete', rows => {
      this.$confirm(`确定要删除吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        delAppVersions({ id: rows.id }).then(res => {
          this.$message.success('删除成功')
          // this.delLastPageItem()
          if (this.pages.total % this.pages.pageSize === 1) {
            const lastpage = (this.pages.total + this.pages.pageSize - 1) / this.pages.pageSize
            if (this.pages.pageNum == lastpage) {
              this.pages.pageNum = this.pages.pageNum - 1
            }
          }
          this.getTableData()
        })
      })
    })
  },
  destroyed() {
    this.$bus.$off('handleDetail')
    this.$bus.$off('handleQRCode')
    this.$bus.$off('handleDelete')
    this.$bus.$off('handleEdit')
  },
  methods: {
    getTableData() {
      getAppVersions({
        skipCount: ((this.pages.pageNum <= 1 ? 1 : this.pages.pageNum) - 1) * this.pages.pageSize,
        maxResultCount: this.pages.pageSize,
      }).then(res => {
        this.tableData = res.items
        this.pages.total = res.totalCount
      })
    },
    handleAddDialog() {
      this.visible = true
      this.dialogTitle = '新增版本'
      this.dialogData = {}
    },
    handleDialogSubmit() {
      this.$refs.appForm.validate().then(async valid => {
        if (!valid) return
        const editModel = this.dialogData
        if (this.dialogData.id) {
          const params = {
            id: editModel.id,
            packageName: editModel.packageName,
            clientType: editModel.clientType,
            version: editModel.version,
            isForcedUpgrade: editModel.isForcedUpgrade,
            updateStrength: editModel.updateStrength,
            remark: editModel.remark,
            publishTime: editModel.publishTime,
            fullPackageUpdate: editModel.fullPackageUpdate,
            fileName: this.fileList[0].name,
            packageAddress: editModel.clientType == 1 ? 'Http://' + editModel.iosUrl : editModel.packageAddress,
          }
          if (params.fullPackageUpdate == false) {
            params.minimumVersionId = editModel.minimumVersion
            params.minimumVersion = this.dropDownList.find(item => item.value == editModel.minimumVersion)['label']
          } else if (params.fullPackageUpdate == true) {
            params.minimumVersionId = ''
            params.minimumVersion = ''
          }
          await putAppVersions(params).then(res => {
            this.$message.success('修改成功')
          })
        } else {
          // if (this.dialogData.fullPackageUpdate == false) {
          //   this.dialogData.minimumVersionId = editModel.minimumVersion
          //   this.dialogData.minimumVersion = this.dropDownList.find(item => item.value == editModel.minimumVersion).label
          // } else if (this.dialogData.fullPackageUpdate == true) {
          //   this.dialogData.minimumVersionId = ''
          //   this.dialogData.minimumVersion = ''
          // }
          const { fullPackageUpdate, minimumVersion } = this.dialogData
          await addAppVersions({
            ...this.dialogData,
            minimumVersion: fullPackageUpdate ? '' : this.dropDownList.find(item => item.value == minimumVersion).label,
            minimumVersionId: fullPackageUpdate ? '' : minimumVersion,
          }).then(res => {
            this.$message.success('新增成功')
          })
        }
        this.fileList = []
        this.handleDialogClose()
        this.getTableData()
      })
    },
    handleDialogClose() {
      this.dialogisDetail = false
      this.fileList = []
      this.visible = false
      this.$refs.appForm.resetFields()
    },
    handleQrDialogClose() {
      this.qrCode = null
      this.qrVisible = false
    },
    handleSizeChange(v) {
      this.pages.pageSize = v
      this.pages.pageNum = 1
      this.getTableData()
    },
    handleCurrentChange(v) {
      this.pages.pageNum = v
      this.getTableData()
    },
    validAppVersion(rule, value, callback) {
      const reg = /^[0-9]+(?:.[0-9]+)+$/
      reg.test(value) ? callback() : callback(new Error('版本号格式不正确,格式应为x.x.x'))
    },
    /* 文件上传 */
    handleRemove(file, fileList) {
      this.fileList = []
      this.dialogData.packageAddress = ''
    },
    handleLocalSuccess(res, file, fileList) {
      if (!res.error) {
        this.$set(this.dialogData, 'fileName', file.name)
        this.$set(this.dialogData, 'packageAddress', public_config.file_api + '/api/file-management/files/www/' + res)
        // this.fileList = [
        //   {
        //     name: file.name,
        //     url: public_config.file_api + '/api/file-management/files/www/' + res,
        //   },
        // ]
      }
    },
    beforeLocalUpload(file) {
      const is5M = file.size / 1024 / 1024 < 500
      if (!is5M) {
        this.$message.error('上传文件大小不能超过 500MB!')
        return false
      }
      return true
    },
    async getOrgDict() {
      const auth = await getAuthConfig()
      const result = await this.$store.dispatch('dicts/getOrgList', { params: { id: auth.organizationsId } })
      return result
    },
    async getDropDownList() {
      const res = await appDropDownList()
      if (res.length) {
        this.dropDownList = res
          .filter(item => item.fullPackageUpdate)
          .map(item => {
            return {
              label: item.version,
              value: item.id,
            }
          })
      } else {
        this.dropDownList = []
      }
      return this.dropDownList
    },
  },
}
</script>

<style lang="scss" scoped>
::v-deep .app-dialog .el-form-item {
  padding: 0;
}
::v-deep .qr-dialog .el-dialog__body {
  text-align: center;
}
</style>
